package cn.com.elite;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;

import cn.com.elite.Util;

public class EliteRecordFtpService extends HttpServlet{
	private static final Log log=LogFactory.getLog(EliteRecordFtpService.class);
	private static Map ip_username_map;
	private static Map username_password_map;
	private static Map username_port_map;
	private static String ContentType;
	public void init(){
		try{
			InputStream inputStream=EliteRecordFtpService.class.getResourceAsStream("eliteftp.properties"); 
			Properties p=new Properties();   
			p.load(inputStream); 
			String count=p.getProperty("COUNT");
			ContentType=p.getProperty("ContentType");
			log.info("init_count:"+count);
			int num=Integer.parseInt(count);
			log.info("init_num:"+num);
			ip_username_map=new HashMap();
			username_password_map=new HashMap();
			username_port_map=new HashMap();
			for(int i=1;i<num+1;i++){
				String ip=p.getProperty("IP"+i);
				String username=p.getProperty("USERNAME"+i);
				String password=p.getProperty("PASSWORD"+i);
				String port=p.getProperty("PORT"+i);
				log.info("ip:"+ip);
				log.info("username:"+username);
				log.info("password:"+password);
				log.info("port:"+port);
				ip_username_map.put(ip,username);
				username_password_map.put(username,password);
				username_port_map.put(username,Integer.parseInt(port));
			}
			log.info("服务初始化读取配置文件完成");
		}catch(Exception e){
			log.error("服务初始化读取配置文件错误");
			log.error(Util.getERRO(e));
		}
	}
	public static void main(String[] args){
		String a="192.168.162.203/1/0/20130723/102/1028432.V3";
		a=a.replaceAll(".*?((\\d{0,3}\\.){3}\\d{0,3}).*","$1");
		System.out.println(a);
	}
	private String getip(String FtpURL) throws Exception{
		String ip=FtpURL;
		ip=ip.replaceAll(".*?((\\d{0,3}\\.){3}\\d{0,3}).*","$1");
		return ip;	
	}
	private String getfileName(String FtpURL) throws Exception{
		String fileName="";
		String FtpURL1=FtpURL.replace("//","");
		fileName=FtpURL1.substring(FtpURL1.indexOf("/"),FtpURL1.length());
		return fileName;
	}
	private String getfileName1(String FtpURL) throws Exception{
		String fileName="";
		fileName=FtpURL.substring(FtpURL.lastIndexOf("/")+1,FtpURL.length());
		return fileName;
	}
	private FTPClient GetFtp(String host,int port,String username,String password){
		FTPClient ftp=new FTPClient();
		try{
			ftp.connect(host, port); 
//			ftp.setControlEncoding("GBK");
//			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
//			conf.setServerLanguageCode("zh");			
			ftp.login(username, password);
			return ftp;
		}catch(Exception e){
			log.error("FTP获取失败");
			log.error(Util.getERRO(e));
			return null;
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response){
		doPost(request,response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response){
		String FtpURL=Util.filter(request.getParameter("FtpURL"));
		log.info("FtpURL:"+FtpURL);
		String Ftptype=Util.filter(request.getParameter("Ftptype"));
		log.info("Ftptype:"+Ftptype);
		FTPClient ftp=null;
		String fileName1="";
		response.setHeader("Cache-Control","no-cache");
		response.setHeader("pragma","no-cache");
		try{
			fileName1=getfileName1(FtpURL);
			log.info("doGet_fileName1:"+fileName1);
			String fileName=getfileName(FtpURL);
			log.info("doGet_fileName:"+fileName);
			String ip=getip(FtpURL);
			log.info("doGet_ip:"+ip);
			String username=Util.filter((String)ip_username_map.get(ip));
			log.info("doGet_username:"+username);
			String password=Util.filter((String)username_password_map.get(username));
			log.info("doGet_password:"+password);
			int port=(Integer)username_port_map.get(username);
			log.info("doGet_port:"+port);
			ftp=GetFtp(ip,port,username,password);
			if(Ftptype.equals("1")){
				InputStream in=ftp.retrieveFileStream(fileName); 
		        BufferedInputStream bis=new BufferedInputStream(in);//输入缓冲流
				response.setCharacterEncoding("UTF-8");
				response.setContentType("text/html;charset=UTF-8");
			    PrintWriter out=response.getWriter();;
			    String return_xml=bis.available()+"";
				log.info("return_xml:"+return_xml);
				out=response.getWriter();
				out.print(return_xml);
				ftp.disconnect();
				log.info("返回完成,FTP关闭");
			}else{
				request.setCharacterEncoding("UTF-8");
				response.setContentType(ContentType);
				response.setHeader("Content-disposition","attachment;filename="+fileName1);
				OutputStream output=response.getOutputStream();
		        InputStream in=ftp.retrieveFileStream(fileName); 
		        BufferedInputStream bis=new BufferedInputStream(in);//输入缓冲流
		        BufferedOutputStream bos=new BufferedOutputStream(output);//输出缓冲流
		        byte data[]=new byte[1024];//缓冲字节数
		        int size=0;
		        size=bis.read(data);
		        while(size!=-1){
		            bos.write(data,0,size);
		            size=bis.read(data);
		        }
		        bis.close();
		        bos.flush();//清空输出缓冲流
		        bos.close();
		        output.close();
				ftp.disconnect();
				log.info("返回完成,FTP关闭");
			}
		}catch(Exception e){
			log.error("doGet过程错误");
			log.error(Util.getERRO(e));	
			try {
				response.setContentType("text/html;charset=UTF-8");
		        PrintWriter out=response.getWriter();
		        out.print("doGet过程错误:"+Util.getERRO(e));
				ftp.disconnect();
			} catch (IOException e1) {
				log.error("FTP关闭错误");
				log.error(Util.getERRO(e1));
			}
		}
		
	}

}
